package com.whc.gateway.fifters;

import com.whc.common.constant.JwtClaimsConstant;
import com.whc.common.constant.RedisHeader;
import com.whc.common.context.BaseContext;
import com.whc.common.utils.JwtUtil;
import com.whc.gateway.properties.AuthProperties;
import com.whc.gateway.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private AuthProperties authProperties;
    @Resource
    private JwtProperties jwtProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求，并查看路经是否需要拦截
        ServerHttpRequest request = exchange.getRequest();
        if(isExclude(request.getPath().toString())){
            //放行
            log.info("放行的路径"+request.getPath().toString());
            return chain.filter(exchange);
        }

        // 3.获取token
        String token = null;
        List<String> headers = request.getHeaders().get(jwtProperties.getUserTokenName());
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }
        //解析token获取其中的userId(第一次判断过期，jwt过期时间给的长)
        String userid="";
        try{
            log.info("校验令牌");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            userid = claims.get(JwtClaimsConstant.USER_ID).toString();
            log.info("网关拦截并获取到了userid:"+userid);
        }catch (ExpiredJwtException e){
            log.info("令牌过期");
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }catch (Exception e){
            log.info("令牌校验失败");
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //第二次通过redis进行短期的判断过期,存在就续期
        if(redisTemplate.hasKey(RedisHeader.userId+userid)){
            log.info("用户{}进行token续期",userid);
            redisTemplate.expire(RedisHeader.userId+userid,5, TimeUnit.MINUTES);
        }


        // 5.传递用户信息
        String userInfo = userid;

        ServerHttpRequest req = exchange.getRequest().mutate()
                .header("user-info", userInfo) // 用户ID存入Subject
                .build();

        return chain.filter(exchange.mutate().request(req).build());

    }
    private boolean isExclude(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, path)) {
                return true;
            }
        }
        return false;
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
